<?php
namespace App\Admin\Controllers\Purchase;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\Supplier;
use App\Models\Product\ProductClassify;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderDetail;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Request;

class DetailController extends AdminController{

    protected $title = '采购明细';

    protected function grid()
    {
        $grid = new Grid(new PurchaseOrderDetail());
//        $grid->model()->with(['purchase' => function($query){
//            //为预加载查询添加额外查询条件
//            $query->where('status','>',1);
////                ->orderBy('id', 'desc');
//        }]);
        $grid->model()->whereHas('purchase',function ($query){
            $query->where('status', '>', PurchaseOrder::STATUS_NO); //未下单
        });
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('purchase_no','订单号');
        $grid->column('purSupplier.name','供应商');
        $grid->column('purchase.pu_user_id','采购员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称')->style('max-width:150px');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('skuClassify.title','品类')->style('max-width:120px');
        $grid->column('order_num','采购数量');
        $grid->column('supplier_price','供应商单价');
        $grid->column('供应商金额')->display(function (){
            return numberFormat(round(($this->order_num ?: 0) * ($this->supplier_price ?: 0),3));
        });
        $grid->column('purchase.status','下单状态')->display(function ($value){
            return PurchaseOrder::$_status[$value];
        });
        $grid->column('purchase.commit_date','交期');
        $grid->column('received_status','收货状态')->display(function ($value){
            return PurchaseOrderDetail::$_receivedStatus[$value];
        });
        $grid->column('rgoods_num','已收货数量');
        $grid->column('purSettlementMethod.settlement_method','结算方式');
        $grid->column('purchase.order_at','下单时间');
        $grid->disableActions();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('purchase/detail-download'));
        });
        $grid->disableCreateButton();
        $grid->disableRowSelector();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('purchase_no','订单号');
                $filter->equal('purchase.supplier_id','供应商')->select(Supplier::options());
                $filter->between('purchase.order_at', '下单日期')->datetime();
            });
            $filter->column(1/2, function ($filter){
                $filter->equal('purchase.status', '下单状态')->select(PurchaseOrder::$_status);
                $filter->equal('received_status', '收货状态')->select(PurchaseOrderDetail::$_receivedStatus);
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
        });
        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = PurchaseOrderDetail::query()
            ->whereHas('purchase',function ($query){
                $query->where('status','>',1);
            })
            ->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if($key == 'purchase'){
                $query->whereHas('purchase', function ($query) use($_filter){
                    foreach ($_filter as $filed => $filter){
                        if(in_array($filed,['order_at'])){
                            if(isset($filter['start'])&&$filter['start']){
                                $query->where('order_at','>=',$filter['start']);
                            }
                            if(isset($filter['end'])&&$filter['end']){
                                $query->where('order_at','<=',$filter['end']);
                            }
                        }else{
                            $query->where($filed, $filter);
                        }
                    }
                });
            }
            if(in_array($key,['purchase_no','received_status','stocking_no','area_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['订单号','供应商','采购员','SKU','产品名称','季节性','品类','采购数量','供应商单价',
            '供应商金额','下单状态','交期','收货状态','已收货数量','结算方式','下单时间','备注'];
        RExcel::exportCsv('采购明细',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->purchase->pu_user_id ?? -1;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $temp = [
                $model->purchase_no,
                $model->purSupplier->name ?? '',
                $seller[$sellerId],
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                ProductClassify::$_season[$model->skuClassify->season ?? 3],
                $model->skuClassify->title ?? '',
                $model->order_num ?: 0,
                $model->supplier_price ?: 0,
                numberFormat(round(($model->order_num ?: 0) * ($model->supplier_price ?: 0),3)),
                array_key_exists(($model->purchase->status ?? -1),PurchaseOrder::$_status) ? PurchaseOrder::$_status[$model->purchase->status] : '-',
                $model->purchase->commit_date ?? '',
                PurchaseOrderDetail::$_receivedStatus[$model->received_status],
                $model->rgoods_num,
                $model->purSettlementMethod->settlement_method ?? '',
                $model->purchase->order_at ?? '',
                $model->purchase->remarks ?? '',
            ];
            yield $temp;
        }
    }
}
